package com.lsh.oms.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.oms.api.model.order.delivery.OrderSendDetailDTO;
import com.lsh.oms.api.model.order.delivery.OrderSendHeadDTO;
import com.lsh.oms.core.constant.LoggerConstant;
import com.lsh.oms.core.enums.YN;
import com.lsh.oms.core.model.calService.CalResultVo;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.proxy.service.BaseProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/9/21
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
public class ComputeServiceUtils {
    /**
     * @param dto
     * @param logSign
     * @param url
     * @return
     */
//    public static CalResultVo requsetCalService4ka(OrderShippingHeadKaDto dto, String logSign, String url, Long venderId) {
//
//        List<OrderShippingDetailKaDto> detailDtos = dto.getShippingDetails();
//        List<Map<Object, Object>> itemList = new ArrayList<>(detailDtos.size());
//        for (OrderShippingDetailKaDto detailDto : detailDtos) {
//            Map<Object, Object> map = new HashMap<>(6);
//            map.put("code", detailDto.getCode());
//            map.put("item_id", detailDto.getItemId() + "");
//            map.put("qty", detailDto.getRealQty());
//
//            itemList.add(map);
//        }
//
//        log.info("{} orderId {} shipping KA itemList {}", new Object[]{logSign, dto.getOrderId(), JSON.toJSONString(itemList)});
//
//        return ComputeServiceUtils.requestCalcService(dto.getOrderId(), itemList, url, logSign, venderId);
//    }


    /**
     * @param dto
     * @param logSign
     * @param url
     * @return
     */
//    public static CalResultVo getCalService4shipping(OrderShippingHeadDto dto, String logSign, String url, Long venderId) {
//
//        List<OrderShippingDetailDto> detailDtos = dto.getDetails();
//        List<Map<Object, Object>> itemList = new ArrayList<>(detailDtos.size());
//        for (OrderShippingDetailDto detailDto : detailDtos) {
//            Map<Object, Object> map = new HashMap<>(5);
//            map.put("item_id", detailDto.getItemId() + "");
//            map.put("qty", detailDto.getRealQty());
//            map.put("code", detailDto.getCode());
//            itemList.add(map);
//        }
//
//        log.info("{} orderId {} shipping itemList {}", new Object[]{logSign, dto.getOrderId(), JSON.toJSONString(itemList)});
//
//        return ComputeServiceUtils.requestCalcService(dto.getOrderId(), itemList, url, logSign, venderId);
//    }

    /**
     * @param dto
     * @param itemMap
     * @param logSign
     * @param url
     * @return
     */
    public static CalResultVo requsetCalService4obd(OrderSendHeadDTO dto, Map<String, BigDecimal> itemMap, String logSign, String url, Long venderId) {

        List<OrderSendDetailDTO> detailDtos = dto.getItems();
        List<Map<Object, Object>> itemList = new ArrayList<>(detailDtos.size());

        for (Map.Entry<String, BigDecimal> detailEntry : itemMap.entrySet()) {
            String[] itemCode = detailEntry.getKey().split(":");
            Map<Object, Object> map = new HashMap<>(6);
            map.put("item_id", itemCode[0]);
            map.put("code", itemCode[1]);
            map.put("qty", detailEntry.getValue());

            itemList.add(map);
        }

        log.info("{} orderId {} shipping rpc itemList {}", new Object[]{logSign, dto.getOrder_id(), JSON.toJSONString(itemList)});

        return ComputeServiceUtils.requestCalcService(dto.getOrder_id(), itemList, url, logSign, venderId);
    }


    /**
     * @param orderCode
     * @param logSign
     * @param url
     * @return
     */
    private static CalResultVo requestCalcService(Long orderCode, List<Map<Object, Object>> itemList, String url, String logSign, Long venderId) {
        DeleveryParams params = new DeleveryParams();
        params.setOrder_id(orderCode + "");
        params.setItemList(itemList);
        CalResultVo calVo = new CalResultVo();
        try {
            log.info(logSign + " 发货获取计算服务请求参数 " + JsonUtils.obj2Json(params));
            long start = System.currentTimeMillis();
            ResultVo<CalResultVo> resultVo = BillsResultUtil.doBiz(params, url, logSign, venderId);

            if (resultVo == null || !YN.N.getValue().equals(resultVo.getRet())) {
                log.info(logSign + "发货获取计算服务失败，订单号:" + orderCode);
            } else {
                log.info(logSign + "发货获取计算服务请求返回" + JsonUtils.obj2Json(resultVo) + ",花费:" + (System.currentTimeMillis() - start) + "ms");
                calVo = resultVo.getData();
            }
        } catch (Throwable e) {
            log.error(logSign + "发货计算服务异常，订单号:" + orderCode);
        }

        return calVo;
    }

    /**
     * @param orderId
     * @param details
     * @param logSign
     * @param url
     * @return
     */
    public static JSONArray getAssemblyResp(String orderId, JSONArray details, String logSign, String url, Long venderId) {
        Iterator iterator = details.iterator();
        while (iterator.hasNext()) {
            JSONObject detail = (JSONObject) iterator.next();
            if (detail.containsKey("ext")) {
                detail.remove("ext");
            }
        }

        Map<String, Object> params = new HashMap<>(8);
        params.put("orderId", orderId);
        params.put("type", 1);
        params.put("sku_list", details.toJSONString());

        log.info(orderId + " sku_list is " + details.toJSONString());
        log.info(orderId + " params is " + JSON.toJSONString(params));
        log.info(orderId + " venderId = " + venderId);
        try {
            LoggerUtils.saveLog(" [GetAssemblyResp][logSign:" + logSign + "][url:" + url + "]", LoggerConstant.LOGGER_INFO);
            HttpMessage httpMessage = HttpUtils.sendPostRequest(url, params, biluderHeader(venderId));
            LoggerUtils.saveLog(" [GetAssemblyResp][logSign:" + logSign + "][return status:" + httpMessage.getStatus() + "]", LoggerConstant.LOGGER_INFO);
            JSONObject detailList = JSONObject.parseObject(BaseProxy.getContent(httpMessage.getMessage()));
            JSONArray detailArray = detailList.getJSONArray("detail_list");
            //TODO
            iterator = detailArray.iterator();
            while (iterator.hasNext()) {
                Object object = iterator.next();
                if (object instanceof JSONArray) {
                    continue;
                }
                JSONObject jsonObject = (JSONObject) object;
                if (jsonObject.get("img_list") != null && !"".equals(jsonObject.get("img_list"))) {
                    JSONArray imgArray = new JSONArray();
                    JSONArray imgTmpArray = jsonObject.getJSONArray("img_list");
                    Iterator imgIterator = imgTmpArray.iterator();
                    while (imgIterator.hasNext()) {
                        Object imgObject = imgIterator.next();
                        if (imgObject instanceof JSONArray) {
                            continue;
                        }
                        JSONObject imgJson = (JSONObject) imgObject;
                        if (imgJson.get("id") != null) {
                            imgArray.add(imgJson.getString("id"));
                        }
                    }
                    jsonObject.put("img_list", imgArray.toJSONString());
                }
            }
            return detailArray;
        } catch (IOException e) {
            LoggerUtils.saveLog(" [GetAssemblyResp][logSign:" + logSign + "][Error Class : " + e.getClass()
                    + ", Error Message : " + e.getMessage() + "]", LoggerConstant.LOGGER_ERROR);
        }

        return null;
    }




    private static Header[] biluderHeader(Long venderId) {

        return new Header[]{
//                new BasicHeader("Content-type", "application/json; charset=utf-8"),
//                new BasicHeader("Accept", "application/json"),
                new BasicHeader("venderId", venderId + "")};

    }


}
